<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Collection;


class PushUrl extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'push:curl';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Push Curl';

    protected $urls;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->urls = new Collection();
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $push = \App\Models\PushUrl::where('status', false)->take(random_int(200, 300))->get();
        $push = $push->groupBy('site');
        $push->each(function ($items, $site) {
            $api = 'http://data.zz.baidu.com/urls?site=' . $site . '&token=' . env('BAIDU_TOKEN');
            $ch = curl_init();
            $options = [
                CURLOPT_URL => $api,
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS => $items->implode('url', "\n"),
                CURLOPT_HTTPHEADER => ['Content-Type: text/plain'],
            ];
            curl_setopt_array($ch, $options);
            $result = curl_exec($ch);
            $res = json_decode($result, JSON_OBJECT_AS_ARRAY);
            if (isset($res['success'])) {
                \App\Models\PushUrl::whereIn('id', $items->pluck('id')->toArray())->update(['status' => true]);
            }
        });
    }
}
